package cn.gzsf.coolshark.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
public class UploadController {

    @RequestMapping("/upload")
    public String upload(MultipartFile picFile) throws IOException {
        //获取文件的原始名称
        String filename = picFile.getOriginalFilename();
        //获取原始名称的后缀
        String suffix = filename.substring(filename.lastIndexOf("."));
        //获得一个新的名称
        filename = UUID.randomUUID()+suffix;
        //准备上传的文件夹：盘符+files+日期文件夹
        String dirPath = "d:/files";
        SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
        String datePath = sdf.format(new Date());
        //如果上传的文件夹不存在，则创建它
        File dirFile = new File(dirPath + datePath);
        if(!dirFile.exists()){
            dirFile.mkdirs();
        }
        //上传文件
        picFile.transferTo(new File(dirPath+datePath+filename));
        //返回上传成功后的url:日期文件夹+文件的名称
        return datePath+filename;
    }

    @RequestMapping("/remove")
    public void remove(String url){
        new File("d:/files"+url).delete();
    }

}
